package com.qipay.sp.excutor.alipay;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.qipay.baas.model.Order;
import com.qipay.scalar.type.ApiTypeEnum;
import com.qipay.sp.excutor.AbstractExcutor;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Component
public class AlipayNativeExcutor extends AbstractExcutor {

    private final static String CONFIG_APPID_NAME="appid";
    private final static String CONFIG_ALIPAY_PUBLIC_NAME="rsa_public_key_alipay";
    private final static String CONFIG_RSA_PRIVATE_NAME="rsa_private_key";
    private final static String API_PARAM_OUT_TRADE_NO="out_trade_no";
    private final static String REQUEST_FROM_URL="request_from_url";
    private final static String API_PARAM_TOTAL_AMOUNT="total_amount";
    private final static String API_PARAM_SUBJECT="suject";
    private final static String API_PARAM_RETURN_URL="return_url";
    private final static String API_PARAM_NOTIFY_URL="notify_url";
    private final static String API_URL="https://openapi.alipay.com/gateway.do";


    @Override
    protected ApiTypeEnum getApiTypeEnum() {
        return ApiTypeEnum.ALIPAY_NATIVE;
    }

    @Override
    protected Map<String, Object> getApiParams(Order order, Map<String, Object> spconfig, Map<String, Object> extendOrderParams) {
        Map<String, Object> apiParams = new HashMap<>();
        apiParams.put(AlipayNativeExcutor.API_PARAM_OUT_TRADE_NO, order.getTradeNo());
        apiParams.put(AlipayNativeExcutor.API_PARAM_SUBJECT, order.getBody());
        apiParams.put(AlipayNativeExcutor.API_PARAM_TOTAL_AMOUNT, order.getActualPayAmount());

        return apiParams;
    }

    @Override
    protected Map<String, Object> run(Map<String, Object> spconfig, Map<String, Object> params) throws Exception {

        Object appId = getVal(spconfig, AlipayNativeExcutor.CONFIG_APPID_NAME);
        Object rsaPrivateKey = getVal(spconfig, AlipayNativeExcutor.CONFIG_RSA_PRIVATE_NAME);
        Object rsaPublicKeyAlipay = getVal(spconfig, AlipayNativeExcutor.CONFIG_ALIPAY_PUBLIC_NAME);
        Object requestFromUrl = getVal(params, AlipayNativeExcutor.REQUEST_FROM_URL);
        Object outTradeNo = getVal(params, AlipayNativeExcutor.API_PARAM_OUT_TRADE_NO);
        Object totalAmount = getVal(params, AlipayNativeExcutor.API_PARAM_TOTAL_AMOUNT);
        Object subject = getVal(params, AlipayNativeExcutor.API_PARAM_SUBJECT);
        Object returnUrl = getVal(params, AlipayNativeExcutor.API_PARAM_RETURN_URL);
        Object notifyUrl = getVal(params, AlipayNativeExcutor.API_PARAM_NOTIFY_URL);

        AlipayClient alipayClient = new DefaultAlipayClient(AlipayNativeExcutor.API_URL, appId.toString(), rsaPrivateKey.toString(), "json", "UTF-8", rsaPublicKeyAlipay.toString(), "RSA2"); // 获得初始化的AlipayClient
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setReturnUrl(returnUrl.toString());
        request.setNotifyUrl(notifyUrl.toString());
        request.setBizContent("{" +
                "\"out_trade_no\":\""+outTradeNo+"\"," +
                "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                "\"total_amount\":"+new BigDecimal((Integer) totalAmount).divide(new BigDecimal(100))+"," +
                "\"subject\":\""+subject+"\"," +
                "\"timeout_express\":\"30m\"," +
                "\"qr_pay_mode\":\"2\"," +
                "\"qrcode_width\":100," +
                "\"request_from_url\":\""+requestFromUrl+"\"" +
                "  }");
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        Map<String, Object> resultMap = new HashMap<>();
        if(response.isSuccess()){
//            String strHtml = response.getBody();
//            String []strings = strHtml.split("\"");
//            String actionUrl = strings[5];
//            String biz_content = strings[11];
//            Map<String, Object> paramMap = new HashMap<>();paramMap.put("biz_content",biz_content);
            //String result = sendFormPost(paramMap,actionUrl);
            //if("invalid")
           // Map<String, Object> responseMap = (Map<String, Object>) JSONObject.parseObject(result);
            resultMap.put("result_code", "0");
            resultMap.put("pay_info", response.getBody());
        } else {
            logger.info("支付宝扫码接口请求失败："+response.getMsg());
            resultMap.put("result_code", "1");
            resultMap.put("message", "支付宝扫码接口请求失败");
        }
        return resultMap;
    }
}
